import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import ApacheClient.ApacheClient;
import Parser.ParseTree;
import Parser.Token;

/**
 *
 * @author Chris
 */
public class BeenVerified {
    private ApacheClient client = new ApacheClient();
    private int queryDelay = 0;
    private int pageDelay = 0;
    private int pDelayRange = 0;
    private int qDelayRange = 0;
//
//    Connection conn = null;
//    String userName = "root";
//    String password = "admin";
//    String url = "jdbc:mysql://localhost/aparna";
    
//    public Connection getConn()
//    {
//    	
//    	try
//    	{
//    	Class.forName ("com.mysql.jdbc.Driver").newInstance ();
//        conn = DriverManager.getConnection (url, userName, password);
//        System.out.println ("Database connection established");
//    	}
//    	
//    	catch(Exception e)
//    	{
//    		e.printStackTrace();
//    	}
//    	
//    	return conn;
//    	  	
//    	}
//    	
    
    	
    
    public BeenVerified() {

    }

    public BeenVerified(int queryDelay, int pageDelay) {
        this.queryDelay = queryDelay;
        this.pageDelay = pageDelay;
    }

    public BeenVerified(int queryDelay, int pageDelay, int qDR, int pDR) {
        this.queryDelay = queryDelay;
        this.pageDelay = pageDelay;
        qDelayRange = qDR;
        pDelayRange = pDR;
    }

    protected void pageDelay() throws Exception {
        // A pointless delay
        Thread.sleep(pageDelay + (int) (Math.random() * pDelayRange));
    }

    protected void queryDelay() throws Exception {
        // A pointless delay
        Thread.sleep(queryDelay + (int) (Math.random() * qDelayRange));
    }

    // Replace unacceptable entries with valid ones
    protected String firstNameQuery(String query) {
        String result[];
        result = query.split(" ");
        return result[0];
    }

    
    protected String lastNameQuery(String query) {
        String result[];
        result = query.split(" ");
        return result[1];
    }
    
    
    public InputStream submitQuery(String query, int page) throws Exception {
        System.out.println("Query is" + query);
        String prefix = "http://results.beenverified.com/f.php?fn=" + firstNameQuery(query) + "&ln=" + lastNameQuery(query)+"&state=" ;
        String suffix = "";
        String urltext;
//        String GetUrl= this.getURL();
        //System.out.println("Url is " + GetUrl);
        //query = firstNameQuery(query) + lastNameQuery(query);

        if (page <= 1)
            urltext = prefix + suffix;
        else
            urltext = prefix + "&page=" + page + "&sz=10";
   System.out.println(urltext);
        return client.getPage(urltext);
    }

    public ArrayList<SearchResult> getResults(String query, int page) throws Exception {
        ArrayList<SearchResult> result = new ArrayList<SearchResult>();
        InputStream content = submitQuery(query, page);
        BufferedReader read = new BufferedReader(new InputStreamReader(content));
        ParseTree tree = new ParseTree(read);
        Token[] tokens = tree.getTokens();
        int outPos;
        int pos;
        int pos2;
        int pos1;
        int pos4;
    
        String name;
        String location;
        String age;
        String att;
        String att1;
        String outerAtt;
        String summary;
        int id;

        // Get the <a ...> tags for Name
//       outPos = tree.findNextTag(0, Token.TD);
//    while(outPos>=0)
//    {
//    	outerAtt = tokens[outPos].valueOfAtt("class"); 
//    	if(outerAtt != null && outerAtt.equalsIgnoreCase("first"))
//    	{
        pos = tree.findNextTag(0, Token.A);
        System.out.println(pos);
            while (pos >= 0) {
        	att = tokens[pos].valueOfAtt("class");
                att1 = tokens[pos].valueOfAtt("href");
                String att2 = tokens[pos].valueOfAtt("id");
        	//IF loop for Name
        	if (att != null && att.equalsIgnoreCase("users") && att1.equalsIgnoreCase("#lightbox_registration_final")) {
              System.out.println("Found column DON");
              pos2 = tree.findNextClose(pos);
              name = tree.getAllText(pos, pos2).toString();
              name.trim();
              if(name != null && name != ""){
        	       System.out.println("Name is " + name);
                }
         
            }
              pos = tree.findNextTag(pos + 1, Token.A);
        }
         
    	
    	   // Get the  tags for address
        pos1 = tree.findNextTag(0, Token.DIV);
        System.out.println(pos1);
       while (pos1 >= 0){
           att = tokens[pos1].valueOfAtt("class");
        if (att != null && att.equalsIgnoreCase("full_name")) {
              System.out.println("Found column Snoopy");
              pos2 = tree.findNextClose(pos1);
        	       System.out.println("Location is " + tree.getAllText(pos1, pos2).toString());
                name = tree.getAllText(pos1, pos2).toString();
         
            }
        pos1 = tree.findNextTag(pos1 + 1, Token.DIV);
       }
        
       // Get the  tags for Phone
        pos4 = tree.findNextTag(0, Token.DIV);
        System.out.println(pos4);
       while (pos4 >= 0){
           att = tokens[pos4].valueOfAtt("class");
        if (att != null && att.equalsIgnoreCase("phone")) {
              System.out.println("Found column Tring Tring");
              pos2 = tree.findNextClose(pos4);
        	       System.out.println("Location is " + tree.getAllText(pos4, pos2).toString());
                name = tree.getAllText(pos4, pos2).toString();
         
            }
        pos4 = tree.findNextTag(pos4 + 1, Token.DIV);ss
       }
       
       
         /* 	if (att != null && att.equalsIgnoreCase("column ix2")) {
                //url = tokens[pos].valueOfAtt("a");
                 
          		
              //  String location = String(tree.getAllTextInsideToken(pos));
               // tokens[pos].getAllTextInsideToken(pos);
                pos2 = tree.findNextTag(pos + 1, Token.DIV);
                pos3 = tree.findNextTag(pos2 + 1, Token.DIV);
              System.out.println("Name is " + tree.getAllText(pos, pos3));
                summary = tree.getAllText(pos2, pos3).toString();
                
                if (!name.startsWith("Name/Aliases")) {
              	  /* pstmt.setInt(1, id);  
              	   pstmt.setString(2, name); 
              	   
              	   
              	   result.add(new SearchResult(name, summary));
              	   
              	   
                  }
                
                
               
            }*/
        	
        	
        	
        	/*if (att != null && att.equalsIgnoreCase("column ix1")) {
                //url = tokens[pos].valueOfAtt("a");
                      
                //String age = tree.getAllTextInsideToken(pos));
               // tokens[pos].getAllTextInsideToken(pos);
                pos2 = tree.findNextTag(pos + 1, Token.DIV);
                pos3 = tree.findNextTag(pos2 + 1, Token.DIV);
                summary = tree.getAllText(pos2, pos3).toString();
               
            }*/
      

        read.close();

        return result;
    }

    public ArrayList<SearchResult> getResults(String query, int startPage, int endPage) throws Exception {
        ArrayList<SearchResult> result = new ArrayList<SearchResult>();

        for (int c = startPage; c <= endPage; c++) {
            result.addAll(getResults(query, c));
        }

        return result;
    }

    public ArrayList<SearchResult> getResultsWithDelay(String query, int startPage, int endPage) throws Exception {
        ArrayList<SearchResult> result = new ArrayList<SearchResult>();

        for (int c = startPage; c <= endPage; c++) {
            result.addAll(getResults(query, c));
            pageDelay();
        }

        return result;
    }
    
    
/*   public int getMaxID()
    {
    	conn = getConn();
    	int maxid = 0;
    	try
    	{
    	Statement stmt = conn.createStatement();
		String query = "select max(idperson) from person";
		   //executing query and get the maximum id
		System.out.println(query);
		   ResultSet rs1 = stmt.executeQuery(query);
		   rs1.next();
		   System.out.println("Rs1" + rs1.next());
		   System.out.println(rs1.getInt("idperson"));
		   maxid = rs1.getInt("idperson");
    	}
    	catch(SQLException se)
    	{
    		se.printStackTrace();
    	}
		   
		   return maxid;
    }
    */
    //getmaxID ends
/*    public String getURL () throws Exception{
        String result="" ;
      InputStream content = submitQuery("John Huntsman ", 1);
      BufferedReader read = new BufferedReader(new InputStreamReader(content));
        ParseTree tree = new ParseTree(read);
        Token[] tokens = tree.getTokens();
        int pos;
        int pos2;
        int pos3;
        
         String name;
        String location;
        String age;
        String att;
        String summary;
        int id;
        pos = tree.findNextTag(0, Token.A);
        while (pos >= 0) {
         att = tokens[pos].valueOfAtt("class");
            if (att != null && att.equalsIgnoreCase("search_results_header")) {
                System.out.println(tokens[pos].valueOfAtt("href"));
                url = tokens[pos].valueOfAtt("href");
                pos2 = tree.findNextTag(pos + 1, Token.DIV);
                pos3 = tree.findNextTag(pos2 + 1, Token.SPAN);
                summary = tree.getAllText(pos2, pos3).toString();
                //summary = tree.getAllTextInsideToken(pos2).toString();
             // if (!url.startsWith("http://www.youtube.com")) {
               //     result.add(new SearchResult(url, summary));
               // }
               // System.out.println(url);
            }
            pos = tree.findNextTag(pos + 1, Token.A);
          
        }

        read.close();

        return result;
    }*/

    
}


